<template>
<div>
   <ylheader :leftsvg="true" :title="'问卷调查'" @paperBack="paperBack"></ylheader>
    <div class="loadmore-container" ref="paperWrapper">
      <div class="loadmore-ul">
          <paperIndex :paperObj = "paperObj" @start="startPaper()" v-if="paperObj.paperType&&paperObj.paperType==1"/> 
          <multichoice :paperObj = "paperObj" @goNext="goNext" @checkItem="checkItem" v-else/> 
      </div>
    </div>
    <deletepopup :poptext="poptext" @candelete="$router.go(-1)" @cancledelete="showPop=!showPop" :isshowdeletepopup="showPop" @deleteshow="deleteshow"></deletepopup>
</div>
</template>

<script>
import ylheader from "src/components/yl-header.vue";
import paperIndex from "src/components/topicdetail/paperIndex.vue";
import multichoice from "src/components/topicdetail/multichoice.vue";
import deletepopup from "src/components/deletepopup.vue";
import api from "src/api/index";
export default {
  name: 'paper',
  components: {
    ylheader,
    paperIndex,
    multichoice,
    api,
    deletepopup
  },

  data() {
    return{
      paperObj:{},
      isIndex:true,
      poptext:"你还未完成此次调查，确认要退出吗？",
      showPop:false,
    }
  },

  computed: {},

  watch: {},

  created() {
        this.getPaper().then(data => {
              return this.initScroll();
        }).then(data => {
          this.irefresh();
        });
  },

  mounted() {},

  destroyed() {},

  methods: {
    getPaper(){
      let p = new Promise((resolve, reject) => {
        const params = {paperId:this.$route.query.id}
        api.getPaper(params).then(res=>{
            if(res.code==0){
              this.paperObj = res.data;
              this.initData(res)
            }
             resolve("获取索引....");
        })
      })
      return p;
    },
    startPaper(){
      let p = new Promise((resolve, reject) => {
        const params = {paperId:this.$route.query.id}
        api.startPaper(params).then(res=>{
            if(res.code==0){
              this.paperObj = res.data;
              this.initData(res)
            }
            resolve("获取题目....");
        })
      })
      return p
    },
    initData(res){
        this.$set(this.paperObj,"paperType",res.data.paperType)
        this.paperObj.inputtext=""
        if(this.paperObj.paperQuestion&&this.paperObj.paperQuestion.paperOptions){
          this.paperObj.paperQuestion.paperOptions.forEach((v,i)=>{
            v.isSelected = false;
            v.textContent = "";
          })
        }
    },
    goNext(obj){
        let p = new Promise((resolve, reject) => {
          if(obj.type==2&&this.paperObj.paperQuestion.need==1){//点击下一题，判断必填
              let isNeed = false
              let isMust = true
              if(this.paperObj.paperQuestion.type!=2){//单选或多选
                this.paperObj.paperQuestion.paperOptions.forEach((v,i)=>{
                  if(v.isSelected){
                    isNeed=true
                  }
                  delete v.textEmptyError
                  if(v.isSelected&&v.isTextMust==1&&(typeof(v.textContent)=="undefined"||v.textContent=="")){
                    isMust=false
                    this.$set(v,"textEmptyError",true)
                  }
                })
              }else{//文本
                if(typeof(obj.inputtext)=="undefined"||obj.inputtext==""){
                  isNeed=false
                }else{
                  isNeed=true
                }
              }
              if(!isNeed){
                  this.$toast("这道题必须回答哦")
                  return
              }
              if(!isMust){
                  return
              }
          }
        
          let params = {
            paperId:this.$route.query.id,
            type:obj.type,
            questionId:this.paperObj.paperQuestion.id,
            index:this.paperObj.paperQuestion.index
          }
            let idArr = []
            let contentArr = []
            let paperTextArray = []
            if( this.paperObj.paperQuestion.paperOptions!=null){
              this.paperObj.paperQuestion.paperOptions.forEach((v,i)=>{
                if(v.isSelected){
                  if(v.textContent){
                    const paperTextObj = new Object();
                    paperTextObj.optionId = v.id;
                    paperTextObj.textContent = v.textContent;
                    paperTextArray.push(paperTextObj)
                  }
                  if(this.paperObj.paperQuestion.type==1){//多选
                      idArr.push(v.id)
                      contentArr.push(v.textContent?(v.content+"("+v.textContent+")"):v.content)
                   }else if(this.paperObj.paperQuestion.type==0){//单选
                      params.result=v.id+","
                      params.content=v.textContent?(v.content+"("+v.textContent+")"):v.content
                      if(v.jump!=null){
                        params.jumpId = v.jump
                      }
        
                   }
                }
              })
            }else{//文本题
                params.result = obj.inputtext
                params.content = params.result
              if(this.paperObj.paperQuestion.jumpId!=null){
                params.jumpId=this.paperObj.paperQuestion.jumpId
              }
            }
             if(paperTextArray.length!=0){
               params.paperText =JSON.stringify(paperTextArray)
             }
            if(this.paperObj.paperQuestion.type==1){//多选
              params.result=idArr.join(",")+","
              params.content=contentArr.join(",")
              if(this.paperObj.paperQuestion.jumpId!=null){
                params.jumpId=this.paperObj.paperQuestion.jumpId
              }
            }
            api.lastornext(params).then(res=>{
                if(res.code==0){
                  this.paperObj = res.data;
                  this.recoverPrevious (res.data)
                  this.irefresh()
                }
                resolve("上或下一题...")
            })
        })
        return p
    },
    checkItem(obj){
      //点击出现文本框
      this.paperObj.paperQuestion.paperOptions.forEach((v,i)=>{
         delete v.textEmptyError
        if((this.paperObj.paperQuestion.type==1&&!v.isSelected)||(this.paperObj.paperQuestion.type==0&&v.isSelected)){
          delete v.isTextShow;
        }
        if(this.paperObj.paperQuestion.type==0&&v.id!=obj.id){
            this.$set(v,"isSelected",false)
            //隐藏未选中文本框
        }
      })
      //Vue.$set之前一定要对象内key不存在 不然只会更新值 并不会为该Key添加响应监测
      const isSelectedTemp = obj.isSelected;
      delete obj.isSelected;
      if(this.paperObj.paperQuestion.type==1){//多选
          this.$set(obj,"isSelected",!isSelectedTemp)
      }else{//单选
        this.$set(obj,"isSelected",!isSelectedTemp)
      }
      this.$set(obj,"isTextShow",obj.isText==1&&obj.isSelected?1:0)
    },
    recoverPrevious(obj){//点击上一题恢复选项
      if(obj.paperResult!=null){
           if(obj.paperQuestion.type==1){//多选
            this.paperObj.paperQuestion.paperOptions.forEach((m,j)=>{
              obj.paperResult.result.split(",").forEach((v,i)=>{
                  if(m.id==v){
                      this.$set(m,"isSelected",true)
                      this.$set(m,"isTextShow",m.isText) 
                    if(obj.paperResult.content.indexOf("(")>-1){
                      this.$set(m,"textContent",obj.paperResult.content.match(/\(([^)]+)\)/)[1]) //获取括号内容
                    }
                  }
              })
            })
           }else if(obj.paperQuestion.type==0){//单选
            this.paperObj.paperQuestion.paperOptions.forEach((m,j)=>{
                if(m.id==obj.paperResult.result.substring(0,obj.paperResult.result.length-1)){
                    this.$set(m,"isSelected",true) 
                    this.$set(m,"isTextShow",m.isText) 
                    if(obj.paperResult.content.indexOf("(")>-1){
                      this.$set(m,"textContent",obj.paperResult.content.match(/\(([^)]+)\)/)[1]) //获取括号内容
                    }
                }
            })
           }else{//文本
               this.paperObj.inputtext=obj.paperResult.content 
           } 
      }
    },
    deleteshow(data){
        this.showPop=data;
    },
    paperBack(){
      if(this.paperObj.paperType!=3){//未答完.问卷状态，1未答，2答道中途，3已答完
        this.showPop=true
      }else{
        this.showPop=false
        this.$router.go(-1)
      }
    },
    //初始化scroll
    initScroll() {
      let p = new Promise((resolve, reject) => {
        let paperWrapper = this.$refs.paperWrapper;
        localStorage.tempPageHeight = document.getElementsByClassName(
          "loadmore-ul"
        )[0].scrollHeight;
        let _this = this;
        this.$nextTick(() => {
          _this.myscroll = new iScroll(paperWrapper, {
            preventDefault: false,
            onScrollMove: function() {
            },
            onScrollEnd: function() { },
            onScrollStart: function() {
              if (
                localStorage.tempPageHeight !=
                document.getElementsByClassName("loadmore-ul")[0].scrollHeight
              ) {
                this.refresh();
                localStorage.tempPageHeight = document.getElementsByClassName(
                  "loadmore-ul"
                )[0].scrollHeight;
              }
            }
          });
          resolve("初始化scroll");
        });
      });
      return p;
    },
    irefresh(){
      this.$nextTick(() => {
          setTimeout(() => {
              this.myscroll.refresh();
          }, 10);
      });
    },
  }

}
</script>

<style lang="less" >
.paper-confirm{
  width: 3.3rem;
  height: 0.84rem;
  line-height: 0.86rem;
  font-weight: bold;
  background: #fb685b;
  font-size: 0.3rem;
  border-radius: 0.05rem;
  color: #ffffff
}
</style>

